#include "widget.h"
#include "ui_widget.h"
#include <QPainter>
#include <QMessageBox>
#include <QCloseEvent>
#include <QKeyEvent>
#include <QMouseEvent>

void Widget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.drawPixmap(0, 0, this->width(), this->height(), QPixmap("..\\..\\images\\background.jpg"));

    //QWidget::paintEvent(event);
}

void Widget::closeEvent(QCloseEvent *event)
{
    QString dlgTitle = "消息框";
    QString strInfo = "确定要退出吗";
    QMessageBox::StandardButton result = QMessageBox::question(this, dlgTitle, strInfo, QMessageBox::Yes
                                                                                            | QMessageBox::No| QMessageBox::Cancel);
    if(result == QMessageBox::Yes)
        event->accept();
    else
        event->ignore();
}

void Widget::keyReleaseEvent(QKeyEvent *event)
{
    Q_UNUSED(event);
    qDebug("keyReleaseEvent函数被触发");
}

void Widget::keyPressEvent(QKeyEvent *event)
{
    QPoint  pt=ui->btnMove->pos();

    if ((event->key()==Qt::Key_A) || (event->key()==Qt::Key_Left))
        ui->btnMove->move(pt.x()-20, pt.y());
    else if((event->key()==Qt::Key_D) || (event->key()==Qt::Key_Right))
        ui->btnMove->move(pt.x()+20, pt.y());
    else if((event->key()==Qt::Key_W)  || (event->key()==Qt::Key_Up))
        ui->btnMove->move(pt.x(),    pt.y()-20);
    else if((event->key()==Qt::Key_S) || (event->key()==Qt::Key_Down))
        ui->btnMove->move(pt.x(),    pt.y()+20);

    event->accept(); //被处理,不会再传播到父窗体
    QWidget::keyPressEvent(event);
}

void Widget::showEvent(QShowEvent *event)
{
    Q_UNUSED(event);
    qDebug("showEvent()函数被触发");
}

void Widget::hideEvent(QHideEvent *event)
{
    Q_UNUSED(event);
    qDebug("hideEvent()函数被触发");
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        QPoint pt = event->pos();
        QPointF relapt = event->position();
        QPointF winPt = event->scenePosition();
        QPointF globalPt = event->globalPosition();
        QString str = QString::asprintf("pos() = (%d, %d)\n", pt.x(), pt.y());
        str += QString::asprintf("\\position() = (%.1f, %.1f)\n", relapt.x(), relapt.y());
        str += QString::asprintf("\\sceneposition() = (%.1f, %.1f)\n", winPt.x(), winPt.y());
        str += QString::asprintf("\\globalposition() = (%.1f, %.1f)", globalPt.x(), globalPt.y());

        ui->labMove->setText(str);
        ui->labMove->adjustSize();
        ui->labMove->move(event->pos());
    }
    QWidget::mousePressEvent(event);
}

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    // this->setFocusPolicy(Qt::StrongFocus);  // 允许接收键盘事件
    // this->setFocus();                       // 强制获取焦点
    ui->btnMove->setFocusPolicy(Qt::NoFocus);  // 防止按钮获取焦点
}

Widget::~Widget()
{
    delete ui;
}
